package com.security.config.security.authentication.common;

import com.security.constant.RedisConstant;
import com.security.domain.bo.R;
import com.security.domain.vo.AccountInfo;
import com.security.utils.ResponseUtil;
import com.security.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出登录成功处理器
 *
 * @author DblSun
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request,
                                HttpServletResponse response,
                                Authentication authentication) throws IOException {
        // 退出登录时，清除缓存
        AccountInfo accountInfo = ThreadLocalUtil.get();
        if (accountInfo != null) {
            stringRedisTemplate.opsForHash()
                    .delete(RedisConstant.ApplicationName + RedisConstant.USER_CAPTCHA, accountInfo.getPhone());
            stringRedisTemplate.opsForHash()
                    .delete(RedisConstant.ApplicationName + RedisConstant.USER_INFO, accountInfo.getId().toString());
            stringRedisTemplate.opsForHash()
                    .delete(RedisConstant.ApplicationName + RedisConstant.USER_TOKEN, accountInfo.getId().toString());
        }
        ResponseUtil.sendResponse(response, R.success("退出成功"));
    }
}